import { getCollection, delCollection } from "../../../api/index"
const app = getApp();
Page({
  data: {
    listData: [],
    page: 1,
    pageSize: 10,
    total: 0,
    showLoading: false,
    loadTip: '',
    checkAll: false,
    checkedList: [],
    isSelect: false,
    isLoading: false
  },
  onLoad() {
    this.getList();
  },
  tapItem() {
    this.setData({ isSelect: true });
  },
  jumpItem(e) {
    my.navigateTo({
      url: '../productDetails/productDetails?goodsId=' +e.target.dataset.goodsId+'&sale_user_id='+app.globalData.sale_user_id,
    });
  },
  allCheckChange(e) {
    const { value } = e.detail;
    this.checkedAll(value);
  },
  checkedAll(status) {
    const listData = this.data.listData.map((element) => ({
      ...element,
      checked: status,
    }));
    this.setData({
      listData,
      checkAll: status
    });
  },
  onCheckChange(e) {
    const { id } = e.currentTarget.dataset;
    const { value } = e.detail;
    const { listData } = this.data;
    listData.forEach(element => {
      if (element.id == id) {
        element.checked = value;
      }
    })
    const checkedLength = listData.filter(item => item.checked).length;
    this.setData({ checkAll: checkedLength === listData.length, listData });
  },
  cancel() {
    this.checkedAll(false);
    this.setData({ isSelect: false });
  },
  delItems() {
    const { listData } = this.data;
    const ids = [];
    listData.forEach(item => {
      item.checked && ids.push(item.id);
    })
    if (ids.length === 0) {
      return;
    }
    const idStr = ids.join(',');
    delCollection(idStr).then(res => {
      my.showToast({
        type: 'success',
        content: '操作成功',
        duration: 3000
      });
      this.setData({ isSelect: false });
      this.getList();
    })
  },
  getList(flag) {
    this.setData({ isLoading: true });
    // flag为true时加载更多
    const { page, pageSize } = this.data;
    getCollection({
      page: flag ? page + 1 : 1,
      pageSize
    }).then(res => {
      my.stopPullDownRefresh();
      res.data.forEach(item => {
        item.checked = false;
      })
      let list = [...this.data.listData];
      if (flag) {
        this.setData({
          showLoading: false
        });
        list = [...list, ...res.data];
      } else {
        list = res.data;
      }
      this.setData({
        isLoading: false,
        listData: list,
        total: res.total,
        page: res.current_page
      })
    }).catch(err => {
      my.stopPullDownRefresh();
    })
  },
  onReachBottom() {
    // 页面拉到底部
    const { listData, total } = this.data;
    if (listData.length < total) {
      this.setData({
        showLoading: true
      })
      this.getList(true);
    } else if (total > 4) {
      this.setData({
        loadTip: '加载完成'
      })
    }
  },
  onPullDownRefresh() {
    this.getList();
  }
});
